package cn.tedu.egweibo2.controller;

import cn.tedu.egweibo2.mapper.UserMapper;
import cn.tedu.egweibo2.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo2.pojo.dto.UserRegDTO;
import cn.tedu.egweibo2.pojo.entity.User;
import cn.tedu.egweibo2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("v1/users/")
public class UserController {
            @Autowired
            private UserMapper userMapper;

            //页面注册
    @PostMapping("reg")
    public int Reg(@RequestBody UserRegDTO userRegDTO){
        UserVO userVO = userMapper.selectReg(userRegDTO.getUsername());
        if (userVO!=null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertReg(user);
        return 1;
    }

      //页面登录
    @PostMapping("login")
     public int login(@RequestBody  UserLoginDTO userLoginDTO, HttpSession session){
        UserVO userVO = userMapper.selectReg(userLoginDTO.getUsername());
        if (userVO==null){
            return 3;
        }
        if(userLoginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return 1;
        }
        return 2;
     }

     @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
       UserVO userVO = (UserVO)  session.getAttribute("user");
       return userVO;
     }

     @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
     }
}
